"use strict";

if (location.hash) {
    location.hash = Math.floor(Math.random() * 0xFFFFFF).toString(16);
}
const roomHash = location.hash.substring(1);

const configuration = {
    iceServers: [{
        urls: 'stun:stun.l.google.com:19302' // Google's public STUN server
    }]
};

$(document).ready(function() {

    const $localVideo = $('#localVideo'),
        $remoteVideo = $('#remoteVideo');

    function onSuccess() {};

    function onError(error) {
        console.error(error);
    };

    const roomName = 'observable-' + roomHash;
    let room;
    const drone = new ScaleDrone('zAJt37nyDVVq841v');
    drone.on('open', error => {
        if (error) {
            return onError(error);
        }
        room = drone.subscribe(roomName);
        room.on('open', error => {
            if (error) {
                onError(error);
            }
        });

        room.on('members', members => {
            if (members.length >= 3) {
                return alert('The room is full.');
            }

            const isOfferer = members.length === 2;
            startWebRTC(isOfferer);
            startListentingToSignals();
        });
    });

    function sendMessage(message) {
        // console.log(message);
        if (message.sdp) {
            window.sdp = message.sdp;
        } else if (message.candidate) {
            window.candidate = message.candidate;
        }

        drone.publish({
            room: roomName,
            message: message,
        });
    }

    function localDescCreated(desc) {
        // window.desc = desc;
        pc.setLocalDescription(desc, () => {
            sendMessage({
                'sdp': pc.localDescription
            });
        }, onError);
    }

    function startListentingToSignals() {
        room.on('data', (message, client) => {
            if (!client || client.id === drone.clientId) {
                return;
            }
            if (message.sdp) {
                pc.setRemoteDescription(new RTCSessionDescription(message.sdp), () => {
                    if (pc.remoteDescription.type === 'offer') {
                        pc.createAnswer().then(localDescCreated).catch(onError);
                    }
                }, onError);
            } else if (message.candidate) {
                pc.addIceCandidate(
                    new RTCIceCandidate(message.candidate, onSuccess, onError)
                );
            }
        });
    }

    let pc;
    function startWebRTC(isOfferer) {
        pc = new RTCPeerConnection(configuration);
        const sendChannel = pc.createDataChannel('sendDataChannel01');

        pc.onicecandidate = event => {
            // console.log('on ice candidate.', event);
            console.log('on ice candidate.');
            if (event.candidate) {
                window.candidate = event.candidate;
                sendMessage({candidate: event.candidate});
            }
        };

        if (isOfferer) {
            pc.onnegotiationneeded = () => {
                console.log('on negotiation needed.');
                pc.createOffer().then(localDescCreated).catch(onError);
            }
        }

        pc.onaddstream = event => {
            console.log('on add stream.')
            // $remoteVideo[0].src = URL.createObjectURL(event.stream);
        }

        navigator.mediaDevices.getUserMedia({
            audio: true,
            video: true,
        }).then(stream => {
            // $localVideo[0].srcObject = stream;
            pc.addStream(stream);
        }, onError);
    }
});
